package com.ht.web360.base.config.web;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.resource.NoResourceException;
import com.ht.web360.base.dto.Res;
import com.ht.web360.base.utils.exceptions.MessageException;
import com.ht.web360.base.utils.exceptions.OssException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {
    @ExceptionHandler(MessageException.class)
    public Res<Void> handleMessageException(MessageException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return Res.fail(e.getMessage());
    }

    @ExceptionHandler(IORuntimeException.class)
    public Res<Void> handleIoRuntimeException(IORuntimeException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return Res.fail("服务器IO错误，请稍后重试");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Res<Void> handleHttpMessageNotReadableException (HttpMessageNotReadableException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        log.warn("传入参数错误", e);
        return Res.fail("传入参数错误，请检查输入参数");
    }

    @ExceptionHandler(MultipartException.class)
    public Res<Void> handleMultipartException(MultipartException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        if (e.getMessage().startsWith("Maximum upload size exceeded")) {
            return Res.fail("上传文件过大，请更换文件重试");
        }
        log.warn("MultipartFile 错误", e);
        return Res.fail("上传方式错误，请重试");
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Res<Void> handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        log.error("数据库错误", e);
        return Res.fail("系统错误，请稍后重试");
    }

    @ExceptionHandler(OssException.class)
    public Res<Void> handleOssException(OssException e) {
        log.error("oss 错误", e);
        return Res.fail("对象存储错误，请稍后重试");
    }

    @ExceptionHandler(NumberFormatException.class)
    public Res<Void> handeNumberFormatException(NumberFormatException e) {
        log.error("数字转换错误", e);
        return Res.fail("数据校验错误，请检查输入");
    }

    @ExceptionHandler(NullPointerException.class)
    public Res<Void> handleNullPointerException(NullPointerException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.warn("参数错误", e);
        return Res.fail("参数错误");
    }

    @ExceptionHandler(Exception.class)
    public Res<Void> handleException(Exception e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
        return Res.fail("系统错误，请稍后重试");
    }

    /**
     * JSR303 校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Res<Void> handle(MethodArgumentNotValidException e){
        StringBuilder message = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(err -> {
            message.append(err.getDefaultMessage()).append(".");
        });
        return Res.fail(message.toString());
    }

    /**
     * 数据校验异常
     */
    @ExceptionHandler({DataIntegrityViolationException.class,
            IllegalArgumentException.class})
    public Res<Void> handleDataIntegrityViolationException(Exception e) {
        String message = e.getMessage();
        System.out.println(message);
        if (message.contains("Duplicate entry")) {
            return Res.fail("数据重复，请检查后重试");
        }
        log.warn(message, e);
        return Res.fail("数据异常，请检查后重试");
    }

    @ExceptionHandler({NoResourceFoundException.class, NoResourceException.class})
    public Res<Void> handleNoResourceException(Exception e) {
        return Res.fail("资源为空");
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Res<Void> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.warn(e.getMessage());
        return Res.fail("请求参数错误");
    }
}
